package com.smart.translator.util;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.media.AudioDeviceInfo;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.Intent;
import com.smart.translator.data.AppConfig;

public class SimpleWebSocketTTSPlayer {
    private static final String TAG = "SimpleWebSocketTTS";
    private static final String WS_PATH = "/ws/doubao_tts";
    private static final int SAMPLE_RATE = 8000;
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_MONO;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;

    // 音频输出模式
    public static final int AUDIO_OUTPUT_SPEAKER = 0; // 强制使用扬声器
    public static final int AUDIO_OUTPUT_AUTO = 1;     // 自动选择（耳机优先）

    private WebSocketClient webSocketClient;
    private boolean isConnected = false;
    private AudioTrack audioTrack;
    private Context context;
    private Handler mainHandler;
    private boolean isPlaying = false;
    private String currentPlayingText = "";
    private int audioOutputMode = AUDIO_OUTPUT_SPEAKER; // 默认使用扬声器
    private AppConfig appConfig;
    
    // TTS状态回调接口
    public interface TTSStateCallback {
        void onTTSStart(String text);
        void onTTSEnd(String text);
    }
    
    private TTSStateCallback ttsStateCallback;

    public SimpleWebSocketTTSPlayer(Context context) {
        this.context = context;
        this.mainHandler = new Handler(Looper.getMainLooper());
        // 从SharedPreferences获取配置
        loadAppConfig();
        initWebSocket();
    }
    
    /**
     * 从SharedPreferences加载应用配置
     */
    private void loadAppConfig() {
        try {
            android.content.SharedPreferences prefs = context.getSharedPreferences("app_config", Context.MODE_PRIVATE);
            String serverUrl = prefs.getString("server_url", "qixin.yeshan.fun");
            appConfig = new AppConfig();
            appConfig.setServerUrl(serverUrl);
            Log.d(TAG, "从SharedPreferences加载服务器配置: " + serverUrl);
        } catch (Exception e) {
            Log.e(TAG, "加载配置失败", e);
            // 使用默认配置
            appConfig = new AppConfig();
            appConfig.setServerUrl("qixin.yeshan.fun");
        }
    }
    
    /**
     * 构建WebSocket URL
     */
    private String buildWebSocketUrl() {
        String serverUrl = appConfig != null ? appConfig.getServerUrl() : null;
        if (serverUrl == null || serverUrl.isEmpty()) {
            serverUrl = "qixin.yeshan.fun";
        }
        return "ws://" + serverUrl + WS_PATH;
    }
    
    public void setTTSStateCallback(TTSStateCallback callback) {
        this.ttsStateCallback = callback;
    }
    
    /**
     * 设置音频输出模式
     * @param mode AUDIO_OUTPUT_SPEAKER 强制使用扬声器，AUDIO_OUTPUT_AUTO 自动选择
     */
    public void setAudioOutputMode(int mode) {
        this.audioOutputMode = mode;
        Log.d(TAG, "设置音频输出模式: " + (mode == AUDIO_OUTPUT_SPEAKER ? "扬声器" : "自动选择"));
    }
    
    /**
     * 获取当前音频输出模式
     */
    public int getAudioOutputMode() {
        return audioOutputMode;
    }

    private void initWebSocket() {
        try {
            URI uri = new URI(buildWebSocketUrl());
            webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    isConnected = true;
                    Log.d(TAG, "WebSocket连接成功");
                }

                @Override
                public void onMessage(String message) {
                    Log.d(TAG, "收到文本消息: " + message);
                    if ("[END]".equals(message)) {
                        // TTS播放结束
                        isPlaying = false;
                        String endedText = currentPlayingText;
                        currentPlayingText = "";
                        if (ttsStateCallback != null) {
                            mainHandler.post(() -> ttsStateCallback.onTTSEnd(endedText));
                        }
                        
                        // 发送TTS结束广播，通知其他服务恢复VAD和语音识别
                        Intent intent = new Intent("com.smart.translator.TTS_STATE_CHANGED");
                        intent.putExtra("is_playing", false);
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                        Log.d(TAG, "发送TTS结束广播");
                    }
                }

                @Override
                public void onMessage(ByteBuffer bytes) {
                    byte[] audioData = new byte[bytes.remaining()];
                    bytes.get(audioData);
                    Log.d(TAG, "收到音频数据: " + audioData.length + " 字节");
                    playAudio(audioData);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    isConnected = false;
                    Log.d(TAG, "WebSocket连接关闭: code=" + code + ", reason=" + reason);
                    
                    // 清理WebSocket客户端，避免重用
                    webSocketClient = null;
                }

                @Override
                public void onError(Exception ex) {
                    Log.e(TAG, "WebSocket错误: " + ex.getMessage());
                    
                    // 清理WebSocket客户端，避免重用
                    webSocketClient = null;
                    isConnected = false;
                }
            };
        } catch (Exception e) {
            Log.e(TAG, "WebSocket初始化失败", e);
        }
    }

    public void connect() {
        // 如果WebSocket客户端为null或已断开，重新初始化
        if (webSocketClient == null || !isConnected) {
            Log.d(TAG, "WebSocket客户端需要重新初始化");
            initWebSocket();
        }
        
        if (webSocketClient != null && !isConnected) {
            // 预先设置音频输出到扬声器
            setupAudioOutput();
            webSocketClient.connect();
            Log.d(TAG, "开始连接WebSocket");
        } else if (isConnected) {
            Log.d(TAG, "WebSocket已连接");
        } else {
            Log.e(TAG, "WebSocket客户端初始化失败");
        }
    }

    private void setupAudioOutput() {
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (audioManager != null) {
                // 设置音频模式
                audioManager.setMode(AudioManager.MODE_NORMAL);
                
                if (audioOutputMode == AUDIO_OUTPUT_SPEAKER) {
                    // 强制使用扬声器模式
                    audioManager.setBluetoothA2dpOn(false);
                    audioManager.setSpeakerphoneOn(true); // 强制开启扬声器
                    audioManager.setRouting(AudioManager.MODE_NORMAL, 
                        AudioManager.ROUTE_SPEAKER, 
                        AudioManager.ROUTE_ALL);
                    Log.d(TAG, "强制设置音频输出到扬声器 - 扬声器已开启");
                } else {
                    // 自动选择模式（耳机优先）
                    // 检查是否有蓝牙耳机连接
                    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


                    if (bluetoothAdapter != null && bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_CONNECTED) {
                        // HFP耳机已连接
                        audioManager.setBluetoothScoOn(true);
                        audioManager.startBluetoothSco();
                        audioManager.setSpeakerphoneOn(false);
                        Log.d(TAG, "检测到HFP蓝牙耳机，使用耳机播放");
                    }

//                    else {
//                        // 没有HFP耳机
//                        audioManager.setBluetoothScoOn(false);
//                        audioManager.stopBluetoothSco();
//                        audioManager.setSpeakerphoneOn(true);
//                        Log.d(TAG, "未检测到HFP蓝牙耳机，使用扬声器播放");
//                    }
                    else
                    if (bluetoothAdapter != null && bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP) == BluetoothProfile.STATE_CONNECTED) {
                        // 有蓝牙耳机连接，使用耳机
                        audioManager.setBluetoothA2dpOn(true);
                        audioManager.setSpeakerphoneOn(false); // 关闭扬声器
                        Log.d(TAG, "检测到蓝牙耳机，使用耳机播放");
                    } else {
                        // 没有蓝牙耳机，使用扬声器
                        audioManager.setBluetoothA2dpOn(false);
                        audioManager.setSpeakerphoneOn(true); // 开启扬声器
                        audioManager.setRouting(AudioManager.MODE_NORMAL,
                            AudioManager.ROUTE_SPEAKER,
                            AudioManager.ROUTE_ALL);
                        Log.d(TAG, "未检测到蓝牙耳机，使用扬声器播放");
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "设置音频输出失败", e);
        }
    }

    public void disconnect() {
        if (webSocketClient != null) {
            webSocketClient.close();
            webSocketClient = null; // 设置为null避免重用
        }
        releaseAudio();
        isConnected = false;
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void sendText(String text) {
        if (isConnected && webSocketClient != null) {
            webSocketClient.send(text);
            Log.d(TAG, "发送TTS文本: " + text);
            
            // 通知TTS开始播放
            isPlaying = true;
            currentPlayingText = text;
            if (ttsStateCallback != null) {
                mainHandler.post(() -> ttsStateCallback.onTTSStart(text));
            }
            
            // 发送TTS开始广播，通知其他服务停止VAD和语音识别
            Intent intent = new Intent("com.smart.translator.TTS_STATE_CHANGED");
            intent.putExtra("is_playing", true);
            intent.putExtra("text", text);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            Log.d(TAG, "发送TTS开始广播");
        } else {
            Log.w(TAG, "WebSocket未连接，无法发送TTS文本");
        }
    }

    private void playAudio(byte[] audioData) {
        mainHandler.post(() -> {
            try {
                // 每次播放前都重新设置音频输出模式
                setupAudioOutput();
                
                // 获取音频设备
                AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
                
                AudioDeviceInfo targetDevice = null;
                
                if (audioOutputMode == AUDIO_OUTPUT_SPEAKER) {
                    // 强制使用扬声器
                    for (AudioDeviceInfo device : devices) {
                        if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) {
                            targetDevice = device;
                            break;
                        }
                    }
                    Log.d(TAG, "强制使用扬声器播放，找到设备: " + (targetDevice != null));
                } else {
                    // 自动选择模式
                    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    if (bluetoothAdapter != null && bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP) == BluetoothProfile.STATE_CONNECTED) {
                        // 有蓝牙耳机，优先使用蓝牙设备
                        for (AudioDeviceInfo device : devices) {
                            if (device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP) {
                                targetDevice = device;
                                break;
                            }
                        }
                        if (targetDevice != null) {
                            Log.d(TAG, "使用蓝牙耳机播放");
                        } else {
                            Log.d(TAG, "未找到蓝牙设备，使用默认设备");
                        }
                    } else {
                        // 没有蓝牙耳机，使用扬声器
                        for (AudioDeviceInfo device : devices) {
                            if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) {
                                targetDevice = device;
                                break;
                            }
                        }
                        Log.d(TAG, "未检测到蓝牙耳机，使用扬声器播放");
                    }
                }

                if (audioTrack == null) {
                    int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
                    audioTrack = new AudioTrack.Builder()
                            .setAudioAttributes(new AudioAttributes.Builder()
                                    .setUsage(AudioAttributes.USAGE_MEDIA)
                                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                                    .build())
                            .setAudioFormat(new AudioFormat.Builder()
                                    .setEncoding(AUDIO_FORMAT)
                                    .setSampleRate(SAMPLE_RATE)
                                    .setChannelMask(CHANNEL_CONFIG)
                                    .build())
                            .setBufferSizeInBytes(bufferSize)
                            .build();
                    
                    if (targetDevice != null) {
                        boolean ok = audioTrack.setPreferredDevice(targetDevice);
                        Log.d(TAG, "setPreferredDevice(" + targetDevice.getType() + ") result: " + ok);
                    }
                    audioTrack.play();
                    Log.d(TAG, "AudioTrack初始化完成");
                } else {
                    // 如果AudioTrack已存在，也尝试设置设备
                    if (targetDevice != null) {
                        boolean ok = audioTrack.setPreferredDevice(targetDevice);
                        Log.d(TAG, "重新设置AudioTrack设备(" + targetDevice.getType() + ") result: " + ok);
                    }
                }
                audioTrack.write(audioData, 0, audioData.length);
            } catch (Exception e) {
                Log.e(TAG, "音频播放失败", e);
            }
        });
    }

    private void releaseAudio() {
        if (audioTrack != null) {
            try {
                audioTrack.stop();
                audioTrack.release();
            } catch (Exception e) {
                Log.e(TAG, "释放AudioTrack失败", e);
            }
            audioTrack = null;
        }
    }
} 